<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\model\DetailModel;
use app\model\OrderModel;
use app\model\UserModel;
use app\model\WareModel;
use think\facade\Request;
use think\facade\Validate;


class Detail
{
 //订单增加
    public function add()
    {
        // 获取参数
        // 校验参数
        $params = Request::param();
        
        // $num =Request::param('menu_num');//菜品数量，数组储存
        // $name =Request::param('menu_name');//菜品名，数组储存
        // $price =Request::param('menu_price');//菜品单价，数组储存
        $list = Request::param('foodList');
       
        $validate = Validate::rule([
            //订单
            'num|商品总数' => 'require|between:1,' . PHP_INT_MAX,
            'order_price|商品总价' => 'require|between:1,' . PHP_INT_MAX,
            'user_id|用户ID' => 'require|between:1,' . PHP_INT_MAX,
            'order_status|订单状态' =>  'require|min:0|max:50',
            // 'order_remark|订单备注' => 'require|min:0|max:50',
            //菜品
            // 'menu_num|商品数量' => 'require|between:1,' . PHP_INT_MAX,
            // 'menu_name|商品名称' => 'require|min:0|max:50',
            // 'menu_price|菜品价格' => 'require|between:1,' . PHP_INT_MAX,
        ]);

        if (!$validate->check($params)) {
            echo $validate->getError();
            exit();
        }

        $order['num'] = $params['num'];
        $order['user_table'] = $params['user_table'];
        $order['order_price'] = $params['order_price'];
        $order['user_id'] = $params['user_id'];
        $order['order_status'] = $params['order_status'];
        //如果未填写备注，则默认为无
        $order['order_remark'] = $params['order_remark'];
        if($order['order_remark'] == '' || $order['order_remark'] == 'undefined'){
            $order['order_remark']='无';
        }
        $order['add_time'] = time();
        //生成订单
        $result1 = OrderModel::create($order);
        //取到订单号
        $orderId = $result1['order_id'];
        //------------------------------------------------------------------------------------
        //把菜单转换成数组，然后循环执行添加
        $arr=json_decode($params['foodList'],true);
        dump($arr);
        if($result1){
            for ($i = 0; $i < count($arr); $i++) {
                $detail=DetailModel::create([
                    'order_id'=>$orderId,
                    'ware_id'=>$arr[$i]['id'],
                    'ware_num'=>$arr[$i]['num'],//总数
                    'price'=>$arr[$i]['price'],//总价
                    'add_time'=>time(),
                ]);
            }
        }

        $data = [
            'status' => 0,
            'message' => '',
            'data' => [
                'result1' => $result1,
            ],
        ];
        return json($data);
    }
}